package com.framework.oauthclient.ext;

import cn.hutool.core.util.ObjectUtil;
import com.framework.common.constant.ErrorCode;
import com.framework.common.exception.BusinessException;
import com.framework.common.model.CommonRole;
import com.framework.common.model.UserInfo;
import com.framework.common.util.RedisUtil;
import com.framework.common.util.SpringUtils;
import com.framework.common.util.StringUtils;
import com.framework.oauthclient.util.OauthClient;
import com.framework.oauthclient.vo.OAuthTokenResult;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zzg
 */
public class ClientAuthenticationManager implements AuthenticationManager  {
    public static String prefixRefreshKey = "refresh_key_";
    public static String prefixRole = "ROLE_";
    private OauthClient oauthClient = null;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        BearerTokenAuthenticationToken bearerToken = (BearerTokenAuthenticationToken) authentication;
        String token = bearerToken.getToken();
        RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);
        UserInfo userInfo = redisUtil.get(token);
        // 获取refresh token
        OAuthTokenResult oAuthTokenResult = redisUtil.get(prefixRefreshKey.concat(token));
        // 从缓存中取
        if (StringUtils.isNotEmpty(userInfo)) {
            Authentication authToken = buildAuthentication(token, userInfo, oAuthTokenResult);
            return authToken;
        }

        // 用户已经过期， 但是还在5分钟以内， 刷新token
        if (StringUtils.isEmpty(oauthClient)) {
            oauthClient = SpringUtils.getBean(OauthClient.class);
        }

        // redis已经过期了5分钟
        if (StringUtils.isEmpty(oAuthTokenResult)) {
            // 尝试获取用户信息
            userInfo = oauthClient.userInfo(token);
            // 服务端校验失败
            if (StringUtils.isEmpty(userInfo)) {
                throw new BusinessException(ErrorCode.Common.invalidToken, "用户已过期， 请重新登录");
            } else {
                // 服务器渠道信息
                Authentication authToken = buildAuthentication(token, userInfo, oAuthTokenResult);
                return authToken;
            }
        }

        // 根据refreshToken刷新信息
        oAuthTokenResult = oauthClient.refreshToken(oAuthTokenResult);
        token = oAuthTokenResult.getAccessToken();
        userInfo = oauthClient.userInfo(token);
        Authentication authToken = buildAuthentication(token, userInfo, oAuthTokenResult);

        return authToken;
    }

    private Authentication buildAuthentication(String token, UserInfo userInfo, OAuthTokenResult oAuthTokenResult) {
        List<String> authCode =  userInfo.getAuthCodes();
        Set<CommonRole> set = userInfo.getRoles();
        if (!ObjectUtil.isEmpty(set)) {
            // 角色以 ROLE_ 开头，以区分菜单
            List<String> roles = set.stream().map(it -> prefixRole.concat(it.getCode())).collect(Collectors.toList());
            authCode.addAll(roles);
        }

        List<GrantedAuthority> authorities = authCode
                .stream()
                .map(it -> new SimpleGrantedAuthority(it)).collect(Collectors.toList());

        String refreshToken = StringUtils.EMPTY;
        if (StringUtils.isNotEmpty(oAuthTokenResult)) {
            refreshToken = oAuthTokenResult.getRefreshToken();
        }
        Authentication authToken = new ClientAuthenticationToken(userInfo, authorities, token, refreshToken);

        // context 会保存到httpSession中
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authToken);
        SecurityContextHolder.setContext(context);

        return authToken;
    }
}
